// 控制定时器
export const TikTok = {
    _interval: null,
    _tasks: [],
    init() {
        // 每5ms是1个tik
        this._interval = setInterval(() => {
            this._tasks.forEach(task => {
                task.state++;
                if (task.state >= task.frequency) {
                    task.state = 0;
                    task();
                }
            });
        }, 5);
    },
    stop() {
        clearInterval(this._interval);
        this._interval = null;
    },
    register(task, frequency) {
        task.state = 0;
        task.frequency = frequency;
        task.uuid = Symbol(`${new Date().getTime()}_${Math.floor(Math.random() * 100000)}`);
        this._tasks.push(task);
    },
    unRegister(task) {
        let _index = this._tasks.findIndex(item => item.uuid === task.uuid);
        if (_index !== -1) {
            this._tasks.splice(_index, 1);
        }
    },
    destroy() {
        clearInterval(this._interval);
        this._interval = null;
        this._tasks.length = 0;
    },
};

export function deepCopy(obj) {
    if (typeof obj === "object") {
        let res;
        if (Array.isArray(obj)) {
            res = [];
        } else {
            res = {};
        }
        for (let key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
                res[key] = deepCopy(obj[key]);
            }
        }
        return res;
    } else if (typeof obj === "function") {
        return obj.bind();
    } else {
        return obj;
    }
}

export function caculateWidthHeight(shape) {
    let points = shape.reduce((acc, graph) => {
        acc.push(...graph);
        return acc;
    }, []);
    let xCoords = points.map(item => item[0]);
    let yCoords = points.map(item => item[1]);
    return {
        shapeHeight: Math.max(...yCoords) - Math.min(...yCoords),
        shapeWidth: Math.max(...xCoords) - Math.min(...xCoords),
    };
}

export const tankStore = [];

export const playerChance = {
    player1: 4,
    player2: 4,
};
